<template>
  <div class="page-container">
    <HeadView v-model:is-collapse="isCollapse" />
    <div class="main-container">
      <Aside :is-collapse="isCollapse" />
      <div class="content-container">
        <div class="content">
          <el-row :gutter="20" class="data-cards">
            <el-col :span="6">
              <el-card shadow="hover">
                <template #header>
                  <div class="card-header">
                    <span>总销售额</span>
                  </div>
                </template>
                <div class="card-content">
                  <h2>¥{{ totalSales }}</h2>
                  <div class="trend">
                    <span :class="salesTrend >= 0 ? 'up' : 'down'">
                      {{ Math.abs(salesTrend) }}%
                      <el-icon><component :is="salesTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" /></el-icon>
                    </span>
                    较上周
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover">
                <template #header>
                  <div class="card-header">
                    <span>总订单数</span>
                  </div>
                </template>
                <div class="card-content">
                  <h2>{{ totalOrders }}</h2>
                  <div class="trend">
                    <span :class="orderTrend >= 0 ? 'up' : 'down'">
                      {{ Math.abs(orderTrend) }}%
                      <el-icon><component :is="orderTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" /></el-icon>
                    </span>
                    较上周
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover">
                <template #header>
                  <div class="card-header">
                    <span>总用户数</span>
                  </div>
                </template>
                <div class="card-content">
                  <h2>{{ totalUsers }}</h2>
                  <div class="trend">
                    <span :class="userTrend >= 0 ? 'up' : 'down'">
                      {{ Math.abs(userTrend) }}%
                      <el-icon><component :is="userTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" /></el-icon>
                    </span>
                    较上周
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="6">
              <el-card shadow="hover">
                <template #header>
                  <div class="card-header">
                    <span>管理员数量</span>
                  </div>
                </template>
                <div class="card-content">
                  <h2>{{ totalAdmins }}</h2>
                  <div class="trend">
                    <span :class="adminTrend >= 0 ? 'up' : 'down'">
                      {{ Math.abs(adminTrend) }}%
                      <el-icon><component :is="adminTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" /></el-icon>
                    </span>
                    较上周
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>

          <el-row :gutter="20" class="charts">
            <el-col :span="16">
              <el-card shadow="hover">
                <template #header>
                  <div class="card-header">
                    <span>销售趋势</span>
                    <div style="display: flex; align-items: center; gap: 16px;">
                      <el-radio-group v-model="salesTimeRange" size="small" @change="handleTimeRangeChange">
                        <el-radio-button label="week">本周</el-radio-button>
                        <el-radio-button label="month">本月</el-radio-button>
                        <el-radio-button label="year">全年</el-radio-button>
                      </el-radio-group>
                      <el-button-group size="small">
                        <el-button :type="salesChartType === 'line' ? 'primary' : 'default'" @click="handleSalesChartTypeChange('line')">曲线图</el-button>
                        <el-button :type="salesChartType === 'bar' ? 'primary' : 'default'" @click="handleSalesChartTypeChange('bar')">柱状图</el-button>
                      </el-button-group>
                    </div>
                  </div>
                </template>
                <div ref="salesChart" class="chart"></div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card shadow="hover">
                <template #header>
                  <div class="card-header">
                    <span>商品分类分布</span>
                    <el-button-group style="margin-left: 16px;">
                      <el-button size="small" :type="chartType==='pie'?'primary':'default'" @click="handleCategoryChartTypeChange('pie')">饼图</el-button>
                      <el-button size="small" :type="chartType==='bar'?'primary':'default'" @click="handleCategoryChartTypeChange('bar')">柱状图</el-button>
                      <el-button size="small" :type="chartType==='line'?'primary':'default'" @click="handleCategoryChartTypeChange('line')">曲线图</el-button>
                    </el-button-group>
                  </div>
                </template>
                <div ref="adminChart" class="chart"></div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>
    <Foot />
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import Aside from '@/components/Aside.vue'
import HeadView from '@/components/Head.vue'
import Foot from '@/components/Foot.vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'HomeView',
  components: {
    ArrowUp,
    ArrowDown,
    Aside,
    HeadView,
    Foot
  },
  data () {
    return {
      isCollapse: false,
      totalSales: 0,
      salesTrend: 0,
      totalOrders: 0,
      orderTrend: 0,
      totalUsers: 0,
      userTrend: 0,
      totalAdmins: 0,
      adminTrend: 0,
      salesChart: null,
      adminChart: null,
      salesTimeRange: 'week',
      salesChartInstance: null,
      adminChartInstance: null,
      mockData: {
        month: {
          xAxis: Array.from({ length: 30 }, (_, i) => `${i + 1}日`),
          sales: Array.from({ length: 30 }, () => Math.floor(Math.random() * 20000) + 8000),
          orders: Array.from({ length: 30 }, () => Math.floor(Math.random() * 200) + 80)
        },
        year: {
          xAxis: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
          sales: [150000, 180000, 160000, 190000, 210000, 230000, 220000, 240000, 260000, 280000, 300000, 320000],
          orders: [1500, 1800, 1600, 1900, 2100, 2300, 2200, 2400, 2600, 2800, 3000, 3200]
        }
      },
      weekData: {
        xAxis: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
        sales: [0, 0, 0, 0, 0, 0, 0],
        orders: [0, 0, 0, 0, 0, 0, 0]
      },
      chartType: 'pie',
      categoryChartData: [],
      salesChartType: 'line'
    }
  },
  methods: {
    fetchSalesData (period = 'week') {
      this.$ajax.get('/admin/index/getWeeklyGrowth', {
        params: {
          period: period
        }
      })
        .then(response => {
          const res = response.data
          if (res.code === 0) {
            // 处理返回的数据
            if (period === 'week') {
              // 周数据处理
              const salesArr = [0, 0, 0, 0, 0, 0, 0]
              const ordersArr = [0, 0, 0, 0, 0, 0, 0]
              res.data.forEach(item => {
                // 优先使用 periodName，因为它更准确
                let dayIndex = 0
                if (item.periodName) {
                  // 如果返回的是 periodName ("周一" 到 "周日")
                  const weekMap = { 周一: 0, 周二: 1, 周三: 2, 周四: 3, 周五: 4, 周六: 5, 周日: 6 }
                  dayIndex = weekMap[item.periodName] || 0
                } else if (item.dayOfWeek) {
                  // 如果返回的是 dayOfWeek (1-7)
                  dayIndex = item.dayOfWeek - 1
                }
                if (dayIndex >= 0 && dayIndex < 7) {
                  salesArr[dayIndex] = item.total_sales
                  ordersArr[dayIndex] = item.order_count
                }
              })
              this.weekData.sales = salesArr
              this.weekData.orders = ordersArr
            } else if (period === 'month') {
              // 只显示有数据的日期
              const xAxis = []
              const salesArr = []
              const ordersArr = []

              res.data.forEach(item => {
                xAxis.push(item.periodName + '日')
                salesArr.push(item.total_sales)
                ordersArr.push(item.order_count)
              })

              this.mockData.month = {
                xAxis,
                sales: salesArr,
                orders: ordersArr
              }
            } else if (period === 'year') {
              // 年数据处理 - periodName 是月份 (1-12)
              const salesArr = new Array(12).fill(0)
              const ordersArr = new Array(12).fill(0)

              res.data.forEach(item => {
                const monthIndex = parseInt(item.periodName) - 1
                if (monthIndex >= 0 && monthIndex < 12) {
                  salesArr[monthIndex] = item.total_sales
                  ordersArr[monthIndex] = item.order_count
                }
              })

              this.mockData.year = {
                xAxis: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
                sales: salesArr,
                orders: ordersArr
              }
            }

            // 更新图表
            if (this.salesTimeRange === period && this.salesChartInstance) {
              this.updateSalesChart(period)
            }
          } else {
            ElMessage.error(res.msg || '获取销售趋势数据失败')
          }
        })
        .catch(error => {
          ElMessage.error(error.response?.data?.message || '获取销售趋势数据失败')
        })
    },

    updateSalesChart (period) {
      if (!this.salesChartInstance) return

      let data
      if (period === 'week') {
        data = this.weekData
      } else {
        data = this.mockData[period]
      }

      // 验证数据是否存在且有效
      if (!data || !data.xAxis || !data.sales || !data.orders) {
        console.warn('数据不完整，跳过图表更新')
        return
      }

      // 更新配置，保持完整的结构
      const newOption = {
        xAxis: {
          type: 'category',
          boundaryGap: this.salesChartType === 'bar',
          data: data.xAxis
        },
        yAxis: [
          {
            type: 'value',
            name: '销售额',
            axisLabel: {
              formatter: '¥{value}'
            }
          },
          {
            type: 'value',
            name: '订单数',
            position: 'right'
          }
        ],
        series: [
          {
            name: '销售额',
            type: this.salesChartType,
            smooth: this.salesChartType === 'line',
            data: data.sales,
            itemStyle: {
              color: '#409EFF'
            },
            symbol: this.salesChartType === 'line' ? 'circle' : undefined,
            symbolSize: this.salesChartType === 'line' ? 14 : undefined,
            showSymbol: this.salesChartType === 'line',
            emphasis: {
              focus: 'series',
              label: {
                show: true,
                position: 'top',
                color: '#409EFF',
                fontWeight: 'bold',
                fontSize: 16,
                formatter: function (params) {
                  return '¥' + Number(params.value).toFixed(2)
                }
              }
            }
          },
          {
            name: '订单数',
            type: this.salesChartType,
            smooth: this.salesChartType === 'line',
            yAxisIndex: 1,
            data: data.orders,
            itemStyle: {
              color: '#67C23A'
            },
            symbol: this.salesChartType === 'line' ? 'circle' : undefined,
            symbolSize: this.salesChartType === 'line' ? 14 : undefined,
            showSymbol: this.salesChartType === 'line',
            emphasis: {
              focus: 'series',
              label: {
                show: true,
                position: 'top',
                color: '#67C23A',
                fontWeight: 'bold',
                fontSize: 16,
                formatter: function (params) {
                  return params.value
                }
              }
            }
          }
        ]
      }

      // 使用notMerge: false来合并配置，保持legend状态
      this.salesChartInstance.setOption(newOption, false)
    },

    fetchData () {
      this.$ajax.get('/admin/index/getPriceSum')
        .then(response => {
          const res = response.data
          if (res.code === 0) {
            this.totalSales = res.data.totalSales
            this.salesTrend = parseFloat(res.data.growthRate)
          } else {
            ElMessage.error(res.msg || '获取销售额数据失败')
          }
        })
        .catch(error => {
          ElMessage.error(error.response?.data?.message || '获取销售额数据失败')
        })

      this.$ajax.get('/admin/index/getOrderCount')
        .then(response => {
          const res = response.data
          if (res.code === 0) {
            this.totalOrders = res.data.totalOrders
            this.orderTrend = parseFloat(res.data.growthRate)
          } else {
            ElMessage.error(res.msg || '获取订单数据失败')
          }
        })
        .catch(error => {
          ElMessage.error(error.response?.data?.message || '获取订单数据失败')
        })

      this.$ajax.get('/admin/index/getUserCount')
        .then(response => {
          const res = response.data
          if (res.code === 0) {
            this.totalUsers = res.data.totalUsers
            this.userTrend = parseFloat(res.data.growthRate)
          } else {
            ElMessage.error(res.msg || '获取用户数据失败')
          }
        })
        .catch(error => {
          ElMessage.error(error.response?.data?.message || '获取用户数据失败')
        })

      this.$ajax.get('/admin/index/getAdminCount')
        .then(response => {
          const res = response.data
          if (res.code === 0) {
            this.totalAdmins = res.data.totalAdmins
            this.adminTrend = parseFloat(res.data.growthRate)
          } else {
            ElMessage.error(res.msg || '获取管理员数据失败')
          }
        })
        .catch(error => {
          ElMessage.error(error.response?.data?.message || '获取管理员数据失败')
        })

      this.fetchSalesData()
    },

    handleTimeRangeChange (value) {
      // 根据选择的时间范围动态获取数据
      this.fetchSalesData(value)
    },

    initSalesChart () {
      if (this.salesChartInstance) {
        this.salesChartInstance.dispose()
      }
      this.salesChartInstance = echarts.init(this.$refs.salesChart)

      const data = this.salesTimeRange === 'week' ? this.weekData : this.mockData[this.salesTimeRange]

      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'line'
          }
        },
        legend: {
          data: ['销售额', '订单数'],
          selected: {
            销售额: true,
            订单数: true
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: this.salesChartType === 'bar',
          data: data.xAxis
        },
        yAxis: [
          {
            type: 'value',
            name: '销售额',
            axisLabel: {
              formatter: '¥{value}'
            }
          },
          {
            type: 'value',
            name: '订单数',
            position: 'right'
          }
        ],
        series: [
          {
            name: '销售额',
            type: this.salesChartType,
            smooth: this.salesChartType === 'line',
            data: data.sales,
            itemStyle: {
              color: '#409EFF'
            },
            symbol: this.salesChartType === 'line' ? 'circle' : undefined,
            symbolSize: this.salesChartType === 'line' ? 14 : undefined,
            showSymbol: this.salesChartType === 'line',
            emphasis: {
              focus: 'series',
              label: {
                show: true,
                position: 'top',
                color: '#409EFF',
                fontWeight: 'bold',
                fontSize: 16,
                formatter: function (params) {
                  return '¥' + Number(params.value).toFixed(2)
                }
              }
            }
          },
          {
            name: '订单数',
            type: this.salesChartType,
            smooth: this.salesChartType === 'line',
            yAxisIndex: 1,
            data: data.orders,
            itemStyle: {
              color: '#67C23A'
            },
            symbol: this.salesChartType === 'line' ? 'circle' : undefined,
            symbolSize: this.salesChartType === 'line' ? 14 : undefined,
            showSymbol: this.salesChartType === 'line',
            emphasis: {
              focus: 'series',
              label: {
                show: true,
                position: 'top',
                color: '#67C23A',
                fontWeight: 'bold',
                fontSize: 16,
                formatter: function (params) {
                  return params.value
                }
              }
            }
          }
        ]
      }
      this.salesChartInstance.setOption(option)
    },

    fetchCategoryData () {
      this.$ajax.get('/admin/index/getCategoryGrowth')
        .then(response => {
          const res = response.data
          if (res.code === 0) {
            // 组装饼图数据
            const pieData = res.data.map(item => ({
              value: item.number,
              name: item.name
            }))
            this.initCategoryChart(pieData)
          } else {
            ElMessage.error(res.msg || '获取商品分类分布数据失败')
          }
        })
        .catch(error => {
          ElMessage.error(error.response?.data?.message || '获取商品分类分布数据失败')
        })
    },
    handleCategoryChartTypeChange (type) {
      this.chartType = type
      this.initCategoryChart(this.categoryChartData)
    },
    initCategoryChart (pieData) {
      this.categoryChartData = pieData // 缓存数据，切换类型时复用
      if (this.adminChartInstance) {
        this.adminChartInstance.dispose()
      }
      this.adminChartInstance = echarts.init(this.$refs.adminChart)
      let option = {}
      if (this.chartType === 'pie') {
        option = {
          tooltip: { trigger: 'item' },
          legend: { orient: 'vertical', left: 'left' },
          series: [{
            name: '商品分类分布',
            type: 'pie',
            radius: '50%',
            data: pieData,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }]
        }
      } else if (this.chartType === 'bar') {
        option = {
          tooltip: { trigger: 'axis' },
          xAxis: {
            type: 'category',
            data: pieData.map(i => i.name),
            axisLabel: {
              interval: 0,
              rotate: 30
            }
          },
          yAxis: { type: 'value' },
          series: [{
            name: '数量',
            type: 'bar',
            data: pieData.map(i => i.value),
            emphasis: {
              label: {
                show: true,
                position: 'top',
                formatter: '{@[1]}'
              }
            }
          }]
        }
      } else if (this.chartType === 'line') {
        option = {
          tooltip: { trigger: 'axis' },
          xAxis: {
            type: 'category',
            data: pieData.map(i => i.name),
            axisLabel: {
              interval: 0,
              rotate: 30
            }
          },
          yAxis: { type: 'value' },
          series: [{
            name: '数量',
            type: 'line',
            data: pieData.map(i => i.value),
            emphasis: {
              label: {
                show: true,
                position: 'top',
                formatter: '{@[1]}'
              }
            }
          }]
        }
      }
      this.adminChartInstance.setOption(option)
    },

    handleResize () {
      this.salesChartInstance?.resize()
      this.adminChartInstance?.resize()
    },

    handleSalesChartTypeChange (type) {
      this.salesChartType = type
      // 直接更新图表类型，而不是重新初始化
      if (this.salesChartInstance) {
        const currentOption = this.salesChartInstance.getOption()
        const data = this.salesTimeRange === 'week' ? this.weekData : this.mockData[this.salesTimeRange]

        // 验证数据是否存在且有效
        if (!data || !data.xAxis || !data.sales || !data.orders) {
          console.warn('数据不完整，跳过图表类型切换')
          return
        }

        // 更新series配置
        const newSeries = [
          {
            name: '销售额',
            type: this.salesChartType,
            smooth: this.salesChartType === 'line',
            data: data.sales,
            itemStyle: {
              color: '#409EFF'
            },
            symbol: this.salesChartType === 'line' ? 'circle' : undefined,
            symbolSize: this.salesChartType === 'line' ? 14 : undefined,
            showSymbol: this.salesChartType === 'line',
            emphasis: {
              focus: 'series',
              label: {
                show: true,
                position: 'top',
                color: '#409EFF',
                fontWeight: 'bold',
                fontSize: 16,
                formatter: function (params) {
                  return '¥' + Number(params.value).toFixed(2)
                }
              }
            }
          },
          {
            name: '订单数',
            type: this.salesChartType,
            smooth: this.salesChartType === 'line',
            yAxisIndex: 1,
            data: data.orders,
            itemStyle: {
              color: '#67C23A'
            },
            symbol: this.salesChartType === 'line' ? 'circle' : undefined,
            symbolSize: this.salesChartType === 'line' ? 14 : undefined,
            showSymbol: this.salesChartType === 'line',
            emphasis: {
              focus: 'series',
              label: {
                show: true,
                position: 'top',
                color: '#67C23A',
                fontWeight: 'bold',
                fontSize: 16,
                formatter: function (params) {
                  return params.value
                }
              }
            }
          }
        ]

        // 更新xAxis的boundaryGap
        const newXAxis = {
          ...currentOption.xAxis[0],
          boundaryGap: this.salesChartType === 'bar'
        }

        this.salesChartInstance.setOption({
          xAxis: newXAxis,
          series: newSeries
        }, false)
      }
    }
  },
  mounted () {
    this.fetchData()
    this.initSalesChart()
    this.fetchCategoryData()
    window.addEventListener('resize', this.handleResize)
  },
  beforeUnmount () {
    window.removeEventListener('resize', this.handleResize)
    this.salesChartInstance?.dispose()
    this.adminChartInstance?.dispose()
  }
}
</script>

<style scoped>
.page-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.main-container {
  flex: 1;
  display: flex;
  height: calc(100vh - 60px); /* 头部高度 */
}

.content-container {
  flex: 1;
  padding: 20px;
  background-color: #f5f7fa;
  height: 100%;
  width: 100%;
  overflow-y: auto;
}

.content {
  width: 100%;
  height: 100%;
}

.data-cards {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-content {
  text-align: center;
}

.card-content h2 {
  margin: 10px 0;
  font-size: 24px;
  color: #303133;
}

.trend {
  font-size: 14px;
  color: #909399;
}

.trend .up {
  color: #67C23A;
}

.trend .down {
  color: #F56C6C;
}

.charts {
  margin-top: 20px;
}

.chart {
  height: 400px;
}

.el-card {
  margin-bottom: 20px;
}
</style>
